package com.exploadingelephants.views;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

import com.exploadingelephants.util.Settings;

/**
 * @author Sandro De Zanet
 * 
 */
public class AnimatedMachineThread extends Thread {
    private boolean running;
    private final SurfaceHolder surfaceHolder;
    private final MachineView machineView;

    // desired fps
    private final static int MAX_FPS = 50;
    // maximum number of frames to be skipped
    private final static int MAX_FRAME_SKIPS = 5;
    // the frame period
    private final static int FRAME_PERIOD = 1000 / MAX_FPS;

    /**
     * 
     */
    public AnimatedMachineThread(SurfaceHolder surfaceHolder,
	    MachineView machineView) {
	super();
	this.surfaceHolder = surfaceHolder;
	this.machineView = machineView;
    }

    /**
     * @param running
     */
    public void setRunning(boolean running) {
	this.running = running;
    }

    @Override
    public void run() {
	long startTime;
	long sleepTime;

	while (running) {
	    Canvas c = null;
	    startTime = System.currentTimeMillis();
	    try {
		c = machineView.getHolder().lockCanvas();

		synchronized (machineView.getHolder()) {
		    machineView.render(c);
		    machineView.update();
		}

	    } finally {
		if (c != null) {
		    machineView.getHolder().unlockCanvasAndPost(c);
		}
	    }
	    // max calculation time to given to calculate one frame
	    long timeToSpentPerFrame = (1000 / Settings.FRAMES_PER_SECOND);
	    sleepTime = timeToSpentPerFrame
		    - (System.currentTimeMillis() - startTime);

	    try {
		if (sleepTime <= 0) {
		    sleepTime = Settings.PLAYLOOP_MIN_SLEEPTIME;
		}
		// Log.d("PlayLoopThread", "Sleeptime: " + sleepTime + "ms");
		sleep(sleepTime);
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}

	while (running)
	    ;// wait until the variable was set
    }
}
